import os
import shutil
import datetime

from PIL import Image
from api.info.TargetNode import TargetNode
import cv2

from common.wrapper.orochi_wrapper import important, cost_time
from api.RequestInfo import RequestInfo
from api.ResponseInfo import ResponseInfo
from utils.config import IMAGE_PATH



@important
@cost_time
def process(json_info: dict):
    requestInfo = RequestInfo(json_info)
    return requestInfo



# predict the results according to the model and data
@important
@cost_time
def predict(data:RequestInfo, model,classify_models):
    try_conf_list = [0.25,0.1]
    targetNodes = []
    coordinateNode = []
    error_code = 0
    for conf in try_conf_list:
        results = model(data.image,conf=conf)

        # Show the results
        for r in results:
            r = r.to("cpu")
            im_array = r.orig_img  # plot a BGR numpy array of predictions
            im_array = cv2.cvtColor(im_array, cv2.COLOR_BGR2RGB)
            im = Image.fromarray(im_array)  # RGB PIL image
            for index, b in enumerate(r.boxes):
                (x1, y1, x2, y2) = b.xyxy.numpy().tolist()[0]
                cls = int(b.cls.numpy().tolist()[0])

                temp_img = im.crop((x1, y1, x2, y2))
                if cls == 0:
                    targetNodes.append(TargetNode(temp_img, x1, y1, x2, y2,classify_models))
                else:
                    coordinateNode.append(TargetNode(temp_img, x1, y1, x2, y2,init_color=False))

            if not coordinateNode:
                coordinateNode.append(TargetNode(im,r.orig_shape[0]/2,0,r.orig_shape[0]/2,0))
        if len(targetNodes) < 7:
            error_code = 1002
            targetNodes = []
            continue
        elif len(targetNodes) > 7:
            error_code = 1003
            targetNodes = []
            continue

        try:
            if data.image.startswith("http"):
                # 获取当前日期
                current_date = str(datetime.datetime.now()).replace(":","-").split(".")[0]
                current_save_path = os.path.join(IMAGE_PATH,str(current_date)+".jpg")
                shutil.move(r.path, current_save_path)
        except Exception as e:
            print("删除文件失败")
        break
    if not coordinateNode:
        coordinateNode = [0]
    responseInfo = ResponseInfo(targetNodes,coordinateNode[0],error_code)
    responseInfo.caculate_label(data.use_type,data.use_fuc)
    responseInfo.sessionId = data.sessionId

    return responseInfo.to_json()

